//验证码机制
$.idcode.setCode();

//显示隐藏密码
$(".icon-eye-open").click(function () {
    $("#text").toggle();
    $("#password").toggle();
})
//text框失去焦点把text框的值赋值给password框
function textBlur() {
    $("#password").val($("#text").val());
}
//password框失去焦点把password框的值赋值给text框
function passwordBlur() {
    $("#text").val($("#password").val());
}
// 密码输入框大写状态监听
function capitalTip(id) {
    $('#' + id).after('<div class="capslock" id="capital_password"><i></i><span>大写锁定已开启</span></div>');
    var capital = false; //聚焦初始化，防止刚聚焦时点击Caps按键提示信息显隐错误

    // 获取大写提示的标签，并提供大写提示显示隐藏的调用接口
    var capitalTip = {
        $elem: $('#capital_' + id),
        toggle: function (s) {
            if (s === 'none') {
                this.$elem.hide();
            } else if (s === 'block') {
                this.$elem.show();
            } else if (this.$elem.is(':hidden')) {
                this.$elem.show();
            } else {
                this.$elem.hide();
            }
        }
    }
    $('#' + id).on('keydown.caps', function (e) {
        if (e.keyCode === 20 && capital) { // 点击Caps大写提示显隐切换
            capitalTip.toggle();
        }
    }).on('focus.caps', function () {
        capital = false
    }).on('keypress.caps', function (e) {
        capsLock(e)
    }).on('blur.caps', function (e) {
        //输入框失去焦点，提示隐藏
        capitalTip.toggle('none');
    });

    function capsLock(e) {
        var keyCode = e.keyCode || e.which; // 按键的keyCode
        var isShift = e.shiftKey || keyCode === 16 || false; // shift键是否按住
        if (keyCode === 9) {
            capitalTip.toggle('none');
        } else {
            //指定位置的字符的 Unicode 编码 , 通过与shift键对于的keycode，就可以判断capslock是否开启了
            // 90 Caps Lock 打开，且没有按住shift键
            if (((keyCode >= 65 && keyCode <= 90) && !isShift) || ((keyCode >= 97 && keyCode <= 122) && isShift)) {
                // 122 Caps Lock打开，且按住shift键
                capitalTip.toggle('block'); // 大写开启时弹出提示框
                capital = true;
            } else {
                capitalTip.toggle('none');
                capital = true;
            }
        }
    }
};
//调用提示
capitalTip('password');
//版本切换
$("div[class='switch']").each(function () {
    $this = $(this);
    var onColor = $this.attr("onColor");
    var offColor = $this.attr("offColor");
    var onText = $this.attr("onText");
    var offText = $this.attr("offText");
    var labelText = $this.attr("labelText");

    var $switch_input = $(":only-child", $this);
    $switch_input.bootstrapSwitch({
        onColor: onColor,
        offColor: offColor,
        onText: onText,
        offText: offText,
        labelText: labelText,
        onSwitchChange: function (event, state) {
            var iptname = event.target.id + "value";
            if (!state) {
                layer.msg("已切换中文版本");
            } else {
                layer.msg("English version has been switched");
            }
        }
    });
});
//记住账户密码
var oUser = document.getElementById('username');
var oPswd = document.getElementById('password');
var oRemember = document.getElementById('remember');

//页面初始化时，如果帐号密码cookie存在则填充
if (getCookie('user') && getCookie('pswd')) {
    oUser.value = getCookie('user');
    oPswd.value = getCookie('pswd');
    oRemember.checked = true;
}
//复选框勾选状态发生改变时，如果未勾选则清除cookie
oRemember.onchange = function () {
    if (!this.checked) {
        delCookie('user');
        delCookie('pswd');
    }
};
//设置cookie
function setCookie(name, value, day) {
    var date = new Date();
    date.setDate(date.getDate() + day);
    document.cookie = name + '=' + value + ';expires=' + date;
};
//获取cookie
function getCookie(name) {
    var reg = RegExp(name + '=([^;]+)');
    var arr = document.cookie.match(reg);
    if (arr) {
        return arr[1];
    } else {
        return '';
    }
};
//删除cookie
function delCookie(name) {
    setCookie(name, null, -1);
};
//账户密码提交验证
var n = 0;
$("#btns").on("click", function () {
    indexLogin();
});

$('#username').bind('keyup', function(event) {

    if (event.keyCode == "13") {
        $("#btns").click();
    }
});

$('#password').bind('keyup', function(event) {

    if (event.keyCode == "13") {
        $("#btns").click();
    }
});

//添加 离交 事件
function needVerifyA(loginMetPass) {

    if ($("#username").val()) {
        //请求 后台 是否需要验证码
        var form1 = new FormData();
        form1.append("username", $("#username").val());

        $.ajax({
            url: "http://localhost:8080/oauth/need_verify",
            type: 'POST',
            crossDomain: true,
            cache: false,
            data: form1,
            processData: false,
            contentType: false,
            dataType: "json"
        }).done(function (res, a, c) {

            if (res != "dontneed" && res.indexOf("ddeenn") > -1) {
                $.idcode.certusValidateCode = res.replace("ddeenn", "");
                $.idcode.setCode();
                $("#lcode").show();
                return;
            } else {
                $("#lcode").hide();
                loginMetPass;
            }
        }).fail(function (res, a, b, c) {
            if (res.responseText) {
                layer.msg(eval("(" + res.responseText + ")").message);
                return;
            }
            layer.msg("已经与服务器断连");
        });
    }
}

//添加 离交 事件
function hasVerifyA(loginMetPass) {

    if ($("#username").val()) {
        //请求 后台 是否需要验证码
        var form1 = new FormData();
        form1.append("username", $("#username").val());

        $.ajax({
            url: "http://localhost:8080/oauth/has_verify",
            type: 'POST',
            crossDomain: true,
            cache: false,
            data: form1,
            processData: false,
            contentType: false,
            dataType: "json"
        }).done(function (res, a, c) {

            if (res != "dontneed" && res.indexOf("ddeenn") > -1) {
                // $.idcode.certusValidateCode = res.replace("ddeenn", "");
                $.idcode.setCode();
                $("#lcode").show();
                return;
            } else {
                $("#lcode").hide();
                loginMetPass;
            }
        }).fail(function (res, a, b, c) {
            if (res.responseText) {
                layer.msg(eval("(" + res.responseText + ")").message);
                return;
            }
            layer.msg("已经与服务器断连");
        });
    }
}


$("#username").blur(function(){
    needVerifyA();
})
function loginMet(form) {
    $.ajax({
        url: "http://localhost:8080/oauth/token",
        type: 'POST',
        crossDomain: true,
        cache: false,
        data: form,
        processData: false,
        contentType: false,
        dataType: "json"
    }).done(function (res, a, c) {

        setCookie("access_token", res.value);
        setCookie("expiration", res.expiration);
        // setCookie("refresh_token",res.refreshToken.value);
        setCookie("token_type", res.tokenType);
        setCookie("baseUrl", "http://localhost:8080/");
        window.location.href = "index.html"
    }).fail(function (res, a, b, c) {
        if (res.responseText) {
            layer.msg(eval("(" + res.responseText + ")").message);
            return;
        }
        layer.msg("用户名或密码错误，请稍后重试");
    });
}
function indexLogin(){
    // needVerifyA();
    var userName = $("#username").val();
    var passWord = $("#password").val();
    var code = $("#Txtidcode").val();
    var IsBy = $.idcode.validateCode();

    if (userName === null || userName === "" || userName === undefined) {
        layer.msg('用户名不能为空！');
        return;
    }
    if (passWord === null || passWord === "" || passWord === undefined) {
        layer.msg('密码不能为空！');
        return;
    }
    if(!$("#Txtidcode").is(":hidden")){
        if (code === null || code === "" || code === undefined) {
            layer.msg('验证码不能为空！');
            return;
        }
    }


    if ((userName != "" || passWord != "")) {
        var form  = new FormData();
//        form.action = "http://localhost:8080/oauth/token"
        form.append("grant_type","password");
        form.append("verifyCode",code);
        form.append("username",userName);
        form.append("password",$.md5(passWord));
        form.append("scope","all");
        form.append("client_id","client_1");
        form.append("client_secret","123456");
        hasVerifyA(loginMet(form))
        // loginMet(form);
        // if (n === 2) {
        //
        //     n++;
        //     return;
        // }
        return;
    }
}

// 忘记密码显示隐藏效果
function shforget(){
    var status = $(".login-box").css("display");
    if(status == "none"){
        $(".forget-box").hide();
        $(".login-box").show();
    }else{
        $(".forget-box").show();
        $(".login-box").hide();
    }
}

$("#birthday").datepicker({
    format: 'yyyy-mm-dd'
});

function forget(){
    var workNo = $("#workNo").val();
    var birthday = $("#birthday").val();

    if(workNo == "" || workNo == undefined || workNo == null){
        layer.msg("工号不能为空！");
        return;
    }
    if(birthday == "" || birthday == undefined || birthday == null){
        layer.msg("出生年月日不能为空！");
        return;
    }
    var pwd ="";
    for (var i=0;i<6;i++){
        pwd+=Math.floor(Math.random()*10)
    }
    var md5pwd = $.md5(pwd);
    // var arr ={};
    // arr.userId = workNo;
    // arr.birthday = birthday;
    $.ajax({
        url: "http://localhost:8080/retrievePwd",
        type: 'POST',
        crossDomain: true,
        cache: false,
        data: {"userId":workNo,"birthday":birthday,"pwd":pwd,"md5pwd":md5pwd},
        contentType: "application/x-www-form-urlencoded",
        dataType: "json"
    }).done(function (res, a, c) {
        if (res=="0"){
            layer.msg("工号不存在或者已失效!");
        }else if (res=="1"){
            layer.msg("出生日期错误!");
        }else if (res=="true"){
            layer.msg("提交成功，请注意查收邮件/企业微信！");
        }else if (res=="error"){
            layer.msg("修改成功，请注意查收邮件/企业微信！如果未收到任何信息，请联系营管理部。");
        }else{
            layer.msg("提交出现异常！");
        }
    }).fail(function (res, a, b, c) {
        layer.msg("密码找回失败，请联系运营管理部！");
    });
}